package com.totoro.view.tags;

import com.totoro.pojo.CreditLevel;
import com.totoro.utils.Base64EncryptionUtil;
import com.totoro.utils.WechatTimeUtil;
import lombok.SneakyThrows;
import org.checkerframework.checker.units.qual.C;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author TOTORO
 * @date 2021/7/3 12:48
 * jsp - 自定义函数
 */
public class TotoroFunction {

    /**
     * 将登录之前的Url 加密
     * @param url
     * @return
     */
    public static byte[] base64Encryption(String url){
        return Base64EncryptionUtil.base64Encrypt(url);
    }

    /**
     * 将一段字符串，除首尾，其他加密
     * @param text
     * @return
     */
    public static String ciphertext(String text){
        String start = text.substring(0,1);
        String end = text.substring(text.length()-1, text.length());
        String ciphertext = "";
        for (int i = 0; i < text.length()-2; i++) {
            ciphertext+="*";
        }
        return start+ciphertext+end;
    }

    /**
     * 过滤关键字为Span高亮标签，仅限于产品搜索列表高亮显示-- 集合
     * @param text
     * @param primary
     * @return
     */
    public static String filterKeywords(String text, List<String> primary){
        String returnStr = text;
        for (int i = 0; i < primary.size(); i++) {
            returnStr = returnStr.replaceAll(primary.get(i), "癰"+primary.get(i)+"龖");
        }
        // 将乱码换成正常的
        returnStr = returnStr.replaceAll("癰", "<span class='H'>");
        returnStr = returnStr.replaceAll("龖", "</span>");
        return returnStr;
    }

    /**
     * 过滤关键字为Span高亮标签，仅限于产品搜索列表高亮显示-- 普通字符串
     * @param text
     * @param primary
     * @return
     */
    public static String filterKeywords(String text, String primary){
        return text.replaceAll(primary, "<span class='H'>"+primary+"</span>");
    }

    /**
     * 获取混搭随机数
     * @param length 随机数长度
     * @return
     */
    public static String getRandomChar(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
        StringBuffer sb = new StringBuffer("");
        for(int i=0;i<length;i++){
            int random=(int)(Math.random()*str.length());
            sb.append(str.charAt(random));
        }
        return sb.toString();
    }

    /**
     * 获得服务器地址
     * @return
     */
    public static String getServerAddress(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
    }

    /**
     * 计算
     * @param beforDate The previous time that needs to be calculated
     * @param calculateType A way of calculating the time interval： year or month
     * @return java.lang.String
     */
    @SneakyThrows
    public static String calculateDataGap(String beforDate, String calculateType){
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date date = simpleFormat.parse(beforDate);
        long beforeLong = date.getTime();
        long nowLong = System.currentTimeMillis();
        int days = (int) ((nowLong - beforeLong) / (1000 * 60 * 60 * 24));
        int finalType = calculateType.equals("year")?365:calculateType.equals("month")?30:1;
        return days/finalType+"";
    }

    /**
     * 将字符串进行日期的格式化
     * @param dateStr
     * @return
     */
    @SneakyThrows
    public static String formatDateByString(String dateStr){
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    /**
     * 字符串时间转毫秒数
     * @param dateStr
     * @return
     */
    @SneakyThrows
    public static String getTime(String dateStr){
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
        return date.getTime()+"";
    }

    /**
     * 计算确认收货剩余时间
     * @param shipDate
     * @return
     */
    @SneakyThrows
    public static String formatShipTimeDifference(String shipDate){
        long sevenTimeMillis = (86400000L * 15);
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(shipDate);
        long beforeTimeMillis = (date.getTime() + sevenTimeMillis) / 1000;
        long currTime = System.currentTimeMillis();
        long day = (beforeTimeMillis - currTime / 1000) / (3600 * 24);
        long hour = ((beforeTimeMillis - currTime / 1000) % (3600 * 24)) / 3600;
        return day+"天"+hour+"时";
    }

    /**
     * 计算时间相差了多少天
     * @param beforeDate
     * @param afterDate
     * @return
     */
    @SneakyThrows
    public static String timeDifferenceDay(String beforeDate, String afterDate){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beforeTime = dateFormat.parse(beforeDate);
        Date afterTime = dateFormat.parse(afterDate);
        long diff = afterTime.getTime() - beforeTime.getTime();
        return (diff / (1000 * 60 * 60 * 24))+"";
    }

    /**
     * 格式化数字，保留指定位数小数点
     * @param number
     * @param numberOfDigits
     * @return
     */
    public static Double formatNumber(Double number, Integer numberOfDigits){
        return Double.parseDouble(String.format("%."+numberOfDigits+"f", number));
    }

    /**
     * 天猫订单号转换字符串
     * @param orderStatusCode
     * @return
     */
    public static String orderStatusCodeString(Integer orderStatusCode){
        return orderStatusCode==1?"未付款":orderStatusCode==2?"未发货":orderStatusCode==3?"已发货":orderStatusCode==4?"交易成功":
        orderStatusCode==5?"已评价":orderStatusCode==6?"等待售后":orderStatusCode==7?"售后完成":orderStatusCode==8?"订单已关闭":"交易出现问题";
    }

    /**
     * 一个数组里是否包含某个数字
     * @param number
     * @param args
     * @return
     */
    public static boolean arrayIsContains(int number, int[] args){
        return Arrays.asList(args).contains(number);
    }

    /**
     * 天猫信誉分等级，转换指定文字说明
     * @param score
     * @return
     */
    public static String creditScoreToCharacter(int score){
        String character = score<=250?"心":score<=10000?"钻":score<=500000?"银冠":score>500000?"金冠":"未知";
        return character;
    }

    /**
     * 天猫信誉积分等级，转换图标，等级
     * @param score
     * @return
     */
    public static CreditLevel creditScoreToCreditLevel(int score){
        CreditLevel creditLevel = new CreditLevel();
        // 心级
        if(score >=0 && score < 251 ){
            creditLevel.setLevelImg("/static/img/seller/score_level/level1.gif");
            // 判断等级
            if(score <= 10){
                creditLevel.setImgCount(1);
            } else if(score <= 40){
                creditLevel.setImgCount(2);
            } else if(score <= 90){
                creditLevel.setImgCount(3);
            } else if (score <= 150){
                creditLevel.setImgCount(4);
            } else if(score <= 250){
                creditLevel.setImgCount(5);
            }
        }

        // 钻级
        if(score >= 251 && score < 10001){
            creditLevel.setLevelImg("/static/img/seller/score_level/level2.gif");
            // 等级
            if(score <= 500){
                creditLevel.setImgCount(1);
            } else if(score <= 1000){
                creditLevel.setImgCount(2);
            } else if(score <= 2000){
                creditLevel.setImgCount(3);
            } else if (score <= 5000){
                creditLevel.setImgCount(4);
            } else if(score <= 10000){
                creditLevel.setImgCount(5);
            }
        }

        // 银冠级
        if(score >= 10001 && score < 500001){
            creditLevel.setLevelImg("/static/img/seller/score_level/level3.gif");
            // 等级
            if(score <= 20000){
                creditLevel.setImgCount(1);
            } else if(score <= 50000){
                creditLevel.setImgCount(2);
            } else if(score <= 100000){
                creditLevel.setImgCount(3);
            } else if (score <= 200000){
                creditLevel.setImgCount(4);
            } else if(score <= 500000){
                creditLevel.setImgCount(5);
            }
        }

        // 金冠级
        if(score >= 500001){
            creditLevel.setLevelImg("/static/img/seller/score_level/level4.gif");
            // 等级
            if(score <= 1000000){
                creditLevel.setImgCount(1);
            } else if(score <= 2000000){
                creditLevel.setImgCount(2);
            } else if(score <= 5000000){
                creditLevel.setImgCount(3);
            } else if (score <= 10000000){
                creditLevel.setImgCount(4);
            } else if(score > 10000001){
                creditLevel.setImgCount(5);
            }
        }

        return creditLevel;
    }


    /**
     * 将时间转成微信聊天时间格式
     * @param dateStr
     * @return
     */
    @SneakyThrows
    public static String dateToWechatTime(String dateStr){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(dateStr);
        long time = date.getTime();
        return WechatTimeUtil.weChatFormatTime(time);
    }

    /**
     * 格式化时间
     * @param dateStr
     * @return
     */
    @SneakyThrows
    public static String dateFormatAgain(String dateStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(dateStr);
        String str = simpleDateFormat.format(date);
        return str.replaceAll("-", "").replaceAll(" ","").replaceAll(":", "");
    }

    /**
     * 获取三个月之前的时间字符串
     * @return
     */
    public static String getThreeMonthAgoDate(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long threeMonthLong = 7879680000L;
        Date date = new Date();
        date.setTime(System.currentTimeMillis() - threeMonthLong);
        return simpleDateFormat.format(date);
    }

    /**
     * 获得当前时间 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getNowDate(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }

    /**
     * 调用字符串类的lastIndexOf函数
     * @param string
     * @param ch
     * @return
     */
    public static int lastIndexOf(String string, String ch){
        return string.lastIndexOf(ch);
    }

    /**
     * 获得今天是星期几
     * @return
     */
    public static String getTodayWeek(){
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar= Calendar.getInstance();
        return weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1];
    }

    /**
     * 获得今天是几号
     * @return
     */
    public static int getToDayNumber(){
        Calendar c = Calendar.getInstance();
        int dateNum=c.get(Calendar.DATE);
        return dateNum;
    }

    /**
     * 获得今天年月
     * @return
     */
    public static String getToDayYearMonth(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM");
        return simpleDateFormat.format(new Date());
    }

    /**
     * 正则表达式过滤<img > 标签
     * @param str
     * @return
     */
    public static String cutOutImgPrefix(String str, String imgReplaceStr){
        String regex = "<img[^>]*>";
        return str.replaceAll(regex, imgReplaceStr);
    }

    /**
     * 随机功能
     * @return
     */
    public static boolean randomFunction(){
        int randomNum = new Random().nextInt(15);
        if(randomNum < 7){
            return true;
        } else {
            return false;
        }
    }
}
